package com.travel.struts.action;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.travel.core.DaoFactory;
import com.travel.dao.IUserDao;
import com.travel.struts.form.UserForm;

public class UserAction extends Action {

    private static final Logger LOGGER = LogManager.getLogger(UserAction.class);

    private static final IUserDao USER_DAO = DaoFactory.getDao(IUserDao.class);

    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
            HttpServletResponse response) {
        // UserForm userForm = (UserForm) form;
        String action = request.getParameter("action");
        System.out.println("获取的查询字符串：" + action);
        if (action == null || "".equals(action)) { /* 如果没有操作的动作 */
            return mapping.findForward("error");
        } else if ("login".equals(action)) { /* 如果是登陆 */
            return LoginAction(mapping, form, request, response);
        } else if ("regiet".equals(action)) { /* 如果是登陆 */
            return RegietAction(mapping, form, request, response);
        } else if ("pwd".equals(action)) { /* 如果是登陆 */
            return pwdAction(mapping, form, request, response);
        } else if ("clear".equals(action)) { /* 如果是登陆 */
            return clearAction(mapping, form, request, response);
        }
        request.setAttribute("error", "操作失败！");
        return mapping.findForward("error");
    }

    private ActionForward clearAction(ActionMapping mapping, ActionForm form, HttpServletRequest request,
            HttpServletResponse response) {
        HttpSession session = request.getSession();
        session.removeAttribute("id");
        session.removeAttribute("regiet");
        return mapping.findForward("user");
    }

    private ActionForward pwdAction(ActionMapping mapping, ActionForm form, HttpServletRequest request,
            HttpServletResponse response) {
        UserForm userForm = (UserForm) form;
        response.setContentType("text/html;charset=GBK");
        response.setCharacterEncoding("GBK");
        PrintWriter outWriter = null;
        try {
            outWriter = response.getWriter();
        } catch (IOException e) {
            e.printStackTrace();
        }
        userForm.setName(userForm.getName());
        userForm.setPassword(userForm.getPassword());
        int ret = USER_DAO.updatePassword(userForm);
        if (ret == 0) {
            request.setAttribute("error", "更改口令失败！");
            outWriter.print("<script>alert('更改口令失败！！');history.go(-1);</script>");
        } else {
            outWriter.print("<script>alert('更改口令成功！！');history.go(-1);</script>");
        }
        return null;
    }

    private ActionForward RegietAction(ActionMapping mapping, ActionForm form, HttpServletRequest request,
            HttpServletResponse response) {
        UserForm userForm = (UserForm) form;
        response.setContentType("text/html;charset=GBK");
        response.setCharacterEncoding("GBK");
        PrintWriter outWriter = null;
        try {
            outWriter = response.getWriter();
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println(request.getParameterValues("sex"));
        String[] str = request.getParameterValues("sex");
        if (str.length != 0) {
            for (int i = 0; i < str.length; i++) {
                System.out.println("1+" + str[i]);
            }
        }
        userForm.setName(userForm.getName());
        userForm.setPassword(userForm.getPassword());
        userForm.setAge(userForm.getAge());
        for (int i = 0; i < str.length; i++) {
            userForm.setSex(str[i]);
        }
        userForm.setAddress(userForm.getAddress());
        // 获取并设置密码
        int ret = USER_DAO.register(userForm); // 调用添加管理员信息
        System.out.print("验证结果ret的值:ret=" + ret);
        if (ret == 1) {
            outWriter.print("<script>alert('信息注册成功');history.go(-1);</script>");
        } else if (ret == 2) {
            request.setAttribute("error", "该管理员信息已经添加！"); // 将错误信息保存到error参数中
            outWriter.print("<script>alert('注册的用户名已经存在');history.go(-1);</script>");
        } else {
            request.setAttribute("error", "添加管理员信息失败！");
            // 将错误信息保存到error参数中
            outWriter.print("<script>alert('信息注册失败！');history.go(-1);</script>");
        }
        return null;
    }

    private ActionForward LoginAction(ActionMapping mapping, ActionForm form, HttpServletRequest request,
            HttpServletResponse response) {
        UserForm userForm = (UserForm) form;
        // 以下两行没有看懂
        // userForm.setName(userForm.getName());
        // userForm.setPassword(userForm.getPassword());
        System.out.println(userForm.getName() + " !!!!!!!!!! " + userForm.getPassword());

        response.setContentType("text/html;charset=GBK");
        response.setCharacterEncoding("GBK");
        PrintWriter outWriter = null;
        try {
            outWriter = response.getWriter();
        } catch (IOException e) {
            LOGGER.error(e.getLocalizedMessage(), e);
        }
        /* 将存有信息的formbean传递给DAO业务层处理(查询是否存在该管理员帐号和密码) */
        int ret = USER_DAO.checkManager(userForm);
        System.out.print("验证结果ret的值:ret=" + ret);
        /* 业务层如果返回１，表示验证成功 */
        ActionForward forward = null;
        if (ret == 3) {
            /* 将用户帐号保存在session中 */
            HttpSession session = request.getSession();
            session.setAttribute("regiet", userForm.getName());
            // session.setAttribute("id", str);
            /* 交给控制器，跳转到登陆成功的页面 */
            forward = mapping.findForward("manager");
        } else if (ret == 1) {
            HttpSession session = request.getSession();
            session.setAttribute("regiet", userForm.getName());

            // session.setAttribute("id",str);
            /* 交给控制器，跳转到登陆成功的页面 */
            forward = mapping.findForward("user");
        } else {
            request.setAttribute("error", "您输入的用户名或密码错误！");
            outWriter.print("<script>alert('您输入的用户名或密码错误');history.go(-1);</script>");
        }
        return forward;
    }
}
